package main

import (
	"fmt"
	"io"
	"net"
	"time"
	"zinx/znet"
)

/*
模拟客户端
*/
func main() {
	fmt.Println("client start....")

	time.Sleep(1 * time.Second)
	//1、直接链接远程服务器，得到一个conn链接
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client start err", err)
		return
	}
	for {
		//发送封包的message消息
		dp := znet.NewDataPack()
		binaryMsg, err := dp.Pack(znet.NewMsgPackage(0, []byte("Zinx V0.5 client Test Message")))
		if err != nil {
			fmt.Println("Pack err:", err)
			return
		}
		if _, err := conn.Write(binaryMsg); err != nil {
			fmt.Println("write conn err", err)
		}

		//先读取六中的head部分 得到ID和dataLen
		headData := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, headData); err != nil {
			fmt.Println("read head err:", err)
			break
		}
		//将二进制的head拆包到msg结构体中
		msgHead, err := dp.Unpack(headData)
		if err != nil {
			fmt.Println("client UnPack msgHead err:", err)
			break
		}
		if msgHead.GetMsgLen() > 0 {
			//msg 是有数据的，需要再次读取data数据
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetMsgLen())
			if _, err := io.ReadFull(conn, msg.Data); err != nil {
				fmt.Println("read data err:", err)
				return
			}
			fmt.Println("-------> Recv Server Msg: ID = ", msg.Id, "len = ", msg.DataLen, "data=", string(msg.Data))
		}
		//cpu阻塞
		time.Sleep(1 * time.Second)
	}

}
